<template>
  <ele-modal
    form
    :width="940"
    :model-value="modelValue"
    title="付款详情"
    @update:modelValue="updateModelValue"
  >
    <ele-page>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="98px">
        <el-form-item label="结账类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio-button label="底价">底价</el-radio-button>
            <el-radio-button label="全款">全款</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="应付" prop="pay">
          <el-input v-model="pay" disabled style="width: 150px">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="付款金额" prop="amount">
          <el-input
            v-model="form.amount"
            style="width: 150px"
            :disabled="form.status == 200"
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="付款时间" prop="pay_time">
          <el-date-picker
            :disabled="form.status == 200"
            v-model="form.pay_time"
            class="filter-item"
            type="datetime"
            placeholder="付款时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 230px"
          />
        </el-form-item>
        <el-form-item label="付款凭证" prop="images">
          <image-upload
            :limit="10"
            v-model="form.images"
            :read-only="form.status == 200"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="save"
            v-if="form.status == 0"
          >
            复核完成
          </el-button>
        </el-form-item>
      </el-form>
      <el-table :data="insuranceList" border stripe>
        <el-table-column prop="plate_number" label="车牌号" />
        <el-table-column prop="insurance" label="保险公司" width="100" />
        <el-table-column prop="cate" label="类型" width="80" />
        <el-table-column prop="totalPrice" label="总价" width="100" />
        <el-table-column prop="price" label="价格" width="100" />
        <el-table-column prop="otherPrice" label="加价/车船税" width="110" />
        <el-table-column prop="rebate_amount" label="返点" width="100" />
        <el-table-column prop="pay_amount" label="实际付款" width="100" />
      </el-table>
    </ele-page>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch, computed } from 'vue';
  import { insurancePay, getPayRecordById } from '@/api/company';
  import { EleMessage } from 'ele-admin-plus/es';
  import ImageUpload from '@/components/ImageUpload/index.vue';
  import { useFormData } from '@/utils/use-form-data';
  const emit = defineEmits(['done', 'update:modelValue']);
  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object
  });

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  const pay = computed(() => {
    return insuranceList.value.reduce((sum, item) => {
      let amount = 0;
      const price = parseFloat(item.price || 0);
      const otherPrice = parseFloat(item.otherPrice || 0);
      const rebateAmount = parseFloat(item.rebate_amount || 0);
      const totalPrice = parseFloat(item.totalPrice || 0);

      if (form.type === '底价') {
        if (item.insurance_id == 1 && item.cate === '商业险') {
          amount = price - rebateAmount;
        } else {
          amount = price + otherPrice - rebateAmount;
        }
      } else if (form.type === '全款') {
        amount = totalPrice;
      }

      return sum + amount;
    }, 0);
  });

  /** 表单数据 */
  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: 0,
    status: 0,
    type: '',
    pay_time: '',
    amount: '',
    images: '' // 付款凭证
  });

  const rules = reactive({
    type: [
      {
        required: true,
        message: '请选择结账类型',
        type: 'string',
        trigger: 'blur'
      }
    ],
    images: [
      {
        required: true,
        message: '请上传凭证',
        type: 'string',
        trigger: 'blur'
      }
    ],
    amount: [
      {
        required: true,
        message: '请输入金额',
        type: 'string',
        trigger: 'blur'
      }
    ],
    pay_time: [
      {
        required: true,
        message: '请选择付款时间',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /** 提交 */
  const save = () => {
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      var requestData = Object.assign({}, form);
      requestData.action = '复核';
      requestData.list = JSON.stringify(insuranceList.value);
      insurancePay(requestData)
        .then(() => {
          loading.value = false;
          EleMessage.success('操作成功');
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          console.log(e);
        });
    });
  };
  const insuranceList = ref([]);
  const getPayRecord = () => {
    getPayRecordById({ id: props.data.id, relationType: '保险结账' })
      .then((res) => {
        assignFields({
          ...res.payRecord
        });
        insuranceList.value = res.relationData;
        form.type = insuranceList.value[0].pay_type;
        form.amount = (form.amount * -1).toFixed(2);
      })
      .catch((e) => {
        EleMessage.error(e.message);
      });
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        getPayRecord();
      } else {
        resetFields();
        formRef.value?.clearValidate?.();
        console.log('关闭');
      }
    }
  );
</script>
